package com.ayz.gateway.common.notify;

import lombok.Getter;
import lombok.Setter;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

/**
 * @ClassName NotifyCenter
 * @Description TODO: 单例类 全局上下文的事件发布订阅中心
 * ApplicationEventPublisher的子实现类 具备发布一个事件的功能
 * @Author 快乐的星球
 * @Date 2023/5/28 10:54
 * @Version 1.0
 **/
@Getter
@Setter
public class NotifyCenter implements ApplicationEventPublisher{
    /**
     * 单例类
     */
    private static final NotifyCenter INSTANCE=new NotifyCenter();

    /**
     * 应用程序事件多播器
     */
    private ApplicationEventMulticaster eventMulticaster;
    /**
     * 发布事件的线程池
     */
    private ExecutorService executor;

    private NotifyCenter(){
        this.executor= Executors.newSingleThreadExecutor(new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r,"NotifyCenterThread");
            }
        });
        this.eventMulticaster=new SimpleApplicationEventMulticaster(executor);
    }
    public static NotifyCenter getINSTANCE() {
        return INSTANCE;
    }

    /**
     * 异步发布一个事件 事件发布其实本质上是通过
     * 事件多播器来进行发布的
     * @param event
     */
    @Override
    public void publishApplicationEvent(ApplicationEvent event) {
        this.eventMulticaster.multicastEvent(event);
    }
}
